package com.smallcc.service.impl;

import com.smallcc.dto.OrderDTO;
import com.smallcc.enums.ResultEnum;
import com.smallcc.exception.SellException;
import com.smallcc.service.BuyerService;
import com.smallcc.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 晓风过境
 * @TODO    买家服务实现
 * @date 2018/3/30 11:58
 * @day 30
 * @return $text$
 * @title ${CLASS_NAME}
 * @project_name sell
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
            return checkOrderOwner(openid,orderId);
        }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO ==null) {
            log.error("[取消订单]查不到要修改订单,orderId={}",orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId){
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO ==null) {
            return null;
        }
        if (!orderDTO.getBuyerOpenid().equals(openid)) {
            log.error("[查询订单]订单的openid不一致,openId={},orderId={}", openid, orderId);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
